package cn.sxt.logistics.controller;


import cn.sxt.logistics.pojo.*;
import cn.sxt.logistics.service.IPermissionService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.mockito.internal.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2020-06-13
 */
@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("permissionManager")
    public String permissionManager(){
        return "permissionManager";
    }


    /*根据当前认证的用户的角色信息查询出对应的菜单权限*/
    @RequestMapping("/menu")
    @ResponseBody
    public List<Permission> menu(){
        //从获取Shiro主体对象
        Subject subject = SecurityUtils.getSubject();
        //获取当前登录的身份
        Admin admin = (Admin) subject.getPrincipal();

        List<Permission> permissions = permissionService.selectPermissionsByRoleId(admin.getRoleId());
        return permissions;
    }


    /*权限列表*/
    @RequestMapping("/list")
    @ResponseBody
    public ResultObject list(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             String keyword){

        //创建分页对象
        Page<Map<String,Object>> permissionPage = new Page<>(pageNum,pageSize);

        //创建条件对象
        QueryWrapper<Map<String,Object>> queryWrapper = new QueryWrapper<>();

        if(StringUtils.isNotBlank(keyword)){
            //按照子表的权限名称作为条件
            queryWrapper.like("c.pname",keyword);

            queryWrapper.or();

            //按照父表权限名称作为条件(权限分类搜索)
            queryWrapper.like("p.pname",keyword);
        }


        //安装类型排序
        queryWrapper.orderByAsc("c.type");

        //执行查询方法
        IPage<Map<String, Object>> result = permissionService.selectPermissions(permissionPage, queryWrapper);


        return new ResultObject(result);
    }


    //删除功能
    @GetMapping("/delete")
    @ResponseBody
    public MessageObject delete(Long permissionId){
        /**
         *
         * 判断当前要删除的权限是否是父权限（并且还有子权限数据）
         * 是：不能删除
         * 不是：直接删除
         *
         */
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",permissionId);
        List<Permission> children = permissionService.list(wrapper);


        //有子权限
        if(children.size() > 0){
            return new MessageObject(0,"该权限还有子权限数据，不能删除");
        }

        boolean flag = permissionService.removeById(permissionId);
        MessageObject mo = new MessageObject(1, "删除数据成功");
        if(!flag){
            mo = new MessageObject(0,"删除数据失败，请联系管理员");
        }
        return mo;
    }


    /*跳转到编辑页面*/
    @GetMapping("/permissionEdit")
    public String permissionEdit(Model m, Long permissionId){

        //如果有id说明是修改操作，需要查询出当前管理员的信息回显
        if(permissionId !=null){
            Permission permission = permissionService.getById(permissionId);
            m.addAttribute("permission",permission);
        }

        //查询出所有的父权限（type=menu）就是父权限
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("type","menu");
        List<Permission> parents = permissionService.list(wrapper);

        m.addAttribute("parents",parents);


        return "permissionEdit";
    }



    /*新增数据*/
    @PostMapping("/insert")
    @ResponseBody
    public MessageObject insert(Permission permission){

        //新增管理员
        boolean flag = permissionService.saveOrUpdate(permission);


        MessageObject mo = new MessageObject(1, "新增数据成功");
        if(!flag){
            mo = new MessageObject(0,"新增数据失败，请联系管理员");
        }
        return mo;
    }



    /*修改数据*/
    @PostMapping("/update")
    @ResponseBody
    public MessageObject update(Permission permission){
        //新增管理员
        boolean flag = permissionService.saveOrUpdate(permission);
        MessageObject mo = new MessageObject(1, "修改数据成功");
        if(!flag){
            mo = new MessageObject(0,"修改数据失败，请联系管理员");
        }
        return mo;
    }

    /*获取所有的权限数据，以供角色操作会后使用zTree显示权限数据*/
    @GetMapping("/getAllPermission")
    @ResponseBody
    public List<Permission> getAllPermission(){
        List<Permission> list = permissionService.list();
        return  list;
    }


}

